/**
 * 用户中心功能模块
 * 处理用户信息编辑、密码修改等功能
 */
const UserCenter = {
    // 初始化
    init() {
        this.bindEvents();
        
        // 添加验证码输入框的回车键监听
        $(document).on('keydown', '#captcha-input', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                const $submitBtn = $('#submit-captcha-btn');
                const email = $submitBtn.data('email');
                const type = $submitBtn.data('type');
                const captchaKey = $submitBtn.data('key') || $submitBtn.attr('onclick').match(/'([^']*)'/g)[2].replace(/'/g, '');
                this.submitCaptcha(email, type, captchaKey);
            }
        });
        
        // 检查是否需要显示欢迎消息
        const lastVisit = localStorage.getItem('lastVisit');
        const today = new Date().toDateString();

        if (lastVisit !== today) {
            // 显示欢迎消息
            showSuccess('欢迎回来！');
            localStorage.setItem('lastVisit', today);
        }
    },

    // 绑定事件
    bindEvents() {
        // 修改头像
        $('#editAvatarBtn').on('click', () => this.openAvatarModal());
        $('#avatar-file').on('change', () => this.previewAvatar());
        
        // 修改昵称
        $('#editNicknameBtn').on('click', () => this.openNicknameModal());
        
        // 修改密码
        $('#editPasswordBtn').on('click', () => this.openPasswordModal());
        
        // 修改邮箱
        $('#editEmailBtn').on('click', () => this.openEmailModal());
        $('#send-code-btn').on('click', () => this.sendEmailCode());
        
        // 退出登录
        $('#logoutBtn').on('click', () => this.openLogoutModal());
    },

    // 打开修改头像模态框
    openAvatarModal() {
        const content = `
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="bg-blue-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">修改头像</h3>
                    <button onclick="modal.hide()" 
                        class="w-8 h-8 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-6">
                    <div class="mb-6 text-center">
                        <div class="w-24 h-24 rounded-full mx-auto mb-3 overflow-hidden border-4 border-blue-100">
                            <img src="${$('.user-avatar').attr('src')}" alt="当前头像" id="preview-avatar" class="w-full h-full object-cover">
                        </div>
                    </div>
                    <form id="avatar-form">
                        <div class="mb-6">
                            <label for="avatar-file" class="block text-sm font-medium text-blue-600 mb-2">选择新头像</label>
                            <input type="file" id="avatar-file" class="w-full px-4 py-3 border border-gray-300 rounded-xl" accept="image/*">
                            <div class="text-sm text-gray-500 mt-2">支持jpg、png、gif格式，大小不超过2MB</div>
                        </div>
                        <div class="flex gap-3">
                            <button type="button" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all" onclick="modal.hide()">取消</button>
                            <button type="button" class="flex-1 py-3 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all" onclick="updateAvatar()">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        modal.show(content);

        // 重新绑定文件选择事件
        $('#avatar-file').on('change', () => this.previewAvatar());
    },

    // 预览头像
    previewAvatar() {
        const file = $('#avatar-file')[0].files[0];
        if (!file) return;
        
        // 检查文件类型
        if (!file.type.match('image.*')) {
            showError('请选择图片文件');
            return;
        }

        // 检查文件大小
        if (file.size > 2 * 1024 * 1024) {
            showError('图片大小不能超过2MB');
            return;
        }
        
        // 预览图片
        const reader = new FileReader();
        reader.onload = (e) => {
            $('#preview-avatar').attr('src', e.target.result);
        };
        reader.readAsDataURL(file);
    },

    // 更新头像
    updateAvatar() {
        const file = $('#avatar-file')[0].files[0];
        if (!file) {
            showError('请选择图片文件');
            return;
        }

        // 验证文件类型
        const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif'];
        if (!allowedTypes.includes(file.type)) {
            showError('请选择正确的图片格式（JPG、PNG、GIF）');
            return;
        }

        // 验证文件大小（5MB）
        if (file.size > 5 * 1024 * 1024) {
            showError('图片大小不能超过5MB');
            return;
        }

        // 创建表单数据
        const formData = new FormData();
        formData.append('file', file);

        // 显示上传中状态
        const $btn = $('#avatar-modal .btn-primary');
        this.showLoading($btn);

        // 发送请求
        $.ajax({
            url: '/web/user/updateAvatar',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);

                if (res.code === 1) {
                    showSuccess('头像上传成功');
                    // 更新头像（添加时间戳避免缓存）
                    $('.user-avatar').attr('src', res.data.avatar + '?t=' + new Date().getTime());
                    modal.hide();
                } else {
                    showError(res.msg || '头像上传失败');
                }
            },
            error: (xhr) => {
                this.hideLoading($btn);
                let errorMsg = '网络错误，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg);
            }
        });
    },

    // 打开修改昵称模态框
    openNicknameModal() {
        const currentNickname = $('#currentNickname').text().trim();
        const content = `
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="bg-blue-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">修改昵称</h3>
                    <button onclick="modal.hide()" 
                        class="w-8 h-8 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-6">
                    <form id="nickname-form">
                        <div class="mb-6">
                            <label for="nickname-input" class="block text-sm font-medium text-blue-600 mb-2">新昵称</label>
                            <input type="text" id="nickname-input" class="w-full px-4 py-3 border border-gray-300 rounded-xl" value="${currentNickname}" maxlength="20">
                            <div class="text-sm text-gray-500 mt-2">2-20个字符，支持中英文、数字和符号</div>
                        </div>
                        <div class="flex gap-3">
                            <button type="button" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all" onclick="modal.hide()">取消</button>
                            <button type="button" class="flex-1 py-3 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all" onclick="updateNickname()">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        modal.show(content);
    },

    // 更新昵称
    updateNickname() {
        const nickname = $('#nickname-input').val().trim();

        if (!nickname) {
            showError('昵称不能为空');
            return;
        }

        if (nickname.length < 2) {
            showError('昵称长度不能少于2个字符');
            return;
        }

        if (nickname.length > 20) {
            showError('昵称长度不能超过20个字符');
            return;
        }

        const $btn = $('#nickname-modal .btn-primary');
        this.showLoading($btn);

        $.ajax({
            url: '/web/user/updateNickname',
            type: 'POST',
            data: {
                nickname: nickname
            },
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);

                if (res.code === 1) {
                    showSuccess('昵称修改成功');
                    // 更新页面上的昵称
                    $('#currentNickname').text(nickname);
                    modal.hide();
                } else {
                    showError(res.msg || '昵称修改失败');
                }
            },
            error: (xhr) => {
                this.hideLoading($btn);
                let errorMsg = '网络错误，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg);
            }
        });
    },

    // 打开修改邮箱模态框
    openEmailModal() {
        const currentEmail = $('#currentEmail').text().trim();
        const isBinding = currentEmail === '未绑定';

        // 首次绑定邮箱
        if (isBinding) {
            this.openBindEmailModal();
        } else {
            // 已绑定邮箱，需要先验证原邮箱
            this.openVerifyOldEmailModal(currentEmail);
        }
    },
    
    // 打开首次绑定邮箱的模态框
    openBindEmailModal(token = '') {
        const content = `
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="bg-blue-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">绑定邮箱</h3>
                    <button onclick="modal.hide()" 
                        class="w-8 h-8 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-6">
                    <form id="email-form">
                        <div class="mb-5">
                            <label for="email-input" class="block text-sm font-medium text-blue-600 mb-2">邮箱地址</label>
                            <input type="email" id="email-input" class="w-full px-4 py-3 border border-gray-300 rounded-xl" value="">
                        </div>
                        <div class="mb-6">
                            <label for="email-code" class="block text-sm font-medium text-blue-600 mb-2">验证码</label>
                            <div class="flex gap-2">
                                <input type="text" id="email-code" class="flex-1 px-4 py-3 border border-gray-300 rounded-xl" placeholder="请输入验证码">
                                <button type="button" id="send-code-btn" class="px-4 py-3 bg-gray-100 border border-gray-300 rounded-xl hover:bg-gray-200 whitespace-nowrap transition-all" onclick="sendEmailCode()">
                                    获取验证码
                                </button>
                            </div>
                        </div>
                        <input type="hidden" id="email-token" value="${token}">
                        <div class="flex gap-3">
                            <button type="button" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all" onclick="modal.hide()">取消</button>
                            <button type="button" class="flex-1 py-3 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all" onclick="updateEmail()">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        modal.show(content);
    },
    
    // 打开验证原邮箱的模态框
    openVerifyOldEmailModal(currentEmail) {
        const content = `
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="bg-blue-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">验证当前邮箱</h3>
                    <button onclick="modal.hide()" 
                        class="w-8 h-8 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-6">
                    <div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                        <p class="text-sm text-blue-700">
                            <i class="fas fa-info-circle mr-2"></i>
                            为了您的账户安全，修改邮箱需要先验证您的当前邮箱
                        </p>
                    </div>
                    <form id="verify-old-email-form">
                        <div class="mb-5">
                            <label for="current-email" class="block text-sm font-medium text-blue-600 mb-2">当前邮箱</label>
                            <input type="email" id="current-email" class="w-full px-4 py-3 border border-gray-300 rounded-xl bg-gray-100" value="${currentEmail}" disabled>
                        </div>
                        <div class="mb-6">
                            <label for="old-email-code" class="block text-sm font-medium text-blue-600 mb-2">验证码</label>
                            <div class="flex gap-2">
                                <input type="text" id="old-email-code" class="flex-1 px-4 py-3 border border-gray-300 rounded-xl" placeholder="请输入验证码">
                                <button type="button" id="verify-old-email-btn" class="px-4 py-3 bg-gray-100 border border-gray-300 rounded-xl hover:bg-gray-200 whitespace-nowrap transition-all" onclick="sendVerifyOldEmailCode()">
                                    获取验证码
                                </button>
                            </div>
                        </div>
                        <div class="flex gap-3">
                            <button type="button" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all" onclick="modal.hide()">取消</button>
                            <button type="button" class="flex-1 py-3 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all" onclick="verifyOldEmail()">下一步</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        modal.show(content);
    },

    // 发送邮箱验证码
    sendEmailCode() {
        const email = $('#email-input').val().trim();

        if (!this.validateEmail(email)) {
            showError('请输入正确的邮箱格式');
            return;
        }

        // 先获取图形验证码
        this.showCaptchaModal(email, 'bind');
    },
    
    // 发送验证原邮箱的验证码
    sendVerifyOldEmailCode() {
        const currentEmail = $('#current-email').val().trim();

        // 先获取图形验证码
        this.showCaptchaModal(currentEmail, 'verify_old_email');
    },
    
    // 验证原邮箱
    verifyOldEmail() {
        const code = $('#old-email-code').val().trim();

        if (!code) {
            showError('请输入验证码');
            return;
        }

        const $btn = $('#verify-old-email-form').find('button:contains("下一步")');
        this.showLoading($btn);

        $.ajax({
            url: '/web/user/verifyOldEmail',
            type: 'POST',
            data: {
                code: code
            },
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);

                if (res.code === 1) {
                    // 验证成功，进入绑定新邮箱流程
                    modal.hide();
                    setTimeout(() => {
                        this.openBindEmailModal(res.data.token);
                    }, 300);
                } else {
                    showError(res.msg || '验证失败');
                }
            },
            error: (xhr) => {
                this.hideLoading($btn);
                let errorMsg = '网络错误，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg);
            }
        });
    },

    // 显示图形验证码对话框
    showCaptchaModal(email, type) {
        // 获取图形验证码
        $.ajax({
            url: '/web/user/getCaptcha',
            type: 'GET',
            dataType: 'json',
            success: (res) => {
                if (res.code === 1) {
                    const captchaKey = res.data.key;
                    const captchaBase64 = res.data.base64;
                    
                    // 创建一个新的模态窗口容器
                    if ($('#captcha-modal').length === 0) {
                        $('body').append('<div id="captcha-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 z-[9999] flex items-center justify-center" style="position: fixed;"></div>');
                    }
                    
                    const captchaModalContent = `
                        <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden relative z-[10000]">
                            <div class="bg-blue-500 px-6 py-4 flex items-center justify-between">
                                <h3 class="text-xl font-bold text-white">安全验证</h3>
                                <button onclick="$('#captcha-modal').remove()" 
                                    class="w-8 h-8 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                                    <i class="fas fa-times text-white"></i>
                                </button>
                            </div>
                            <div class="p-6">
                                <div class="mb-5">
                                    <label class="block text-sm font-medium text-blue-600 mb-2">图形验证码</label>
                                    <div class="flex items-center gap-2">
                                        <div class="relative flex-1">
                                            <input type="text" id="captcha-input" class="w-full px-4 py-3 border border-gray-300 rounded-xl" placeholder="请输入验证码">
                                        </div>
                                        <div class="h-12 overflow-hidden border border-gray-300 rounded-xl cursor-pointer" id="captcha-img-container">
                                            <img src="${captchaBase64}" alt="验证码" class="h-full" id="captcha-img" onclick="refreshCaptcha()">
                                        </div>
                                    </div>
                                    <div class="mt-1 text-xs text-gray-500 flex items-center">
                                        <span>看不清？</span>
                                        <button type="button" class="text-blue-500 ml-1" onclick="refreshCaptcha()">点击刷新</button>
                                    </div>
                                </div>
                                <div class="flex gap-3">
                                    <button type="button" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all" onclick="$('#captcha-modal').remove()">取消</button>
                                    <button type="button" id="submit-captcha-btn" class="flex-1 py-3 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all" data-email="${email}" data-type="${type}" data-key="${captchaKey}" onclick="submitCaptcha('${email}', '${type}', '${captchaKey}')">确认</button>
                                </div>
                            </div>
                        </div>
                    `;
                    
                    $('#captcha-modal').html(captchaModalContent);
                    
                    // 防止点击验证码模态窗口的背景时关闭
                    $('#captcha-modal').on('click', function(e) {
                        if (e.target === this) {
                            e.stopPropagation();
                            return false;
                        }
                    });
                    
                    // 让输入框自动获取焦点
                    setTimeout(() => {
                        $('#captcha-input').focus();
                    }, 100);
                } else {
                    showError(res.msg || '获取验证码失败');
                }
            },
            error: () => {
                showError('网络错误，请稍后重试');
            }
        });
    },
    
    // 刷新图形验证码
    refreshCaptcha() {
        $.ajax({
            url: '/web/user/getCaptcha',
            type: 'GET',
            dataType: 'json',
            success: (res) => {
                if (res.code === 1) {
                    $('#captcha-img').attr('src', res.data.base64);
                    // 更新按钮的数据属性
                    const $submitBtn = $('#submit-captcha-btn');
                    const email = $submitBtn.data('email');
                    const type = $submitBtn.data('type');
                    
                    $submitBtn.data('key', res.data.key);
                    $submitBtn.attr('onclick', `submitCaptcha('${email}', '${type}', '${res.data.key}')`);
                } else {
                    showError(res.msg || '刷新验证码失败');
                }
            },
            error: () => {
                showError('网络错误，请稍后重试');
            }
        });
    },
    
    // 提交图形验证码并发送邮箱验证码
    submitCaptcha(email, type, captchaKey) {
        const captcha = $('#captcha-input').val().trim();
        
        if (!captcha) {
            showError('请输入图形验证码');
            return;
        }
        
        const $btn = $('#submit-captcha-btn');
        // 确保从按钮数据属性获取最新的参数
        email = $btn.data('email') || email;
        type = $btn.data('type') || type;
        captchaKey = $btn.data('key') || captchaKey;
        
        this.showLoading($btn);
        
        // 发送邮箱验证码请求
        $.ajax({
            url: '/web/user/sendEmailCode',
            type: 'POST',
            data: {
                email: email,
                type: type,
                captcha: captcha,
                captcha_key: captchaKey
            },
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);
                
                if (res.code === 1) {
                    // 关闭验证码模态窗口，保留原窗口
                    $('#captcha-modal').remove();
                    showSuccess('验证码已发送，请查收邮件');
                    this.handleCodeSent(type);
                } else {
                    showError(res.msg || '验证码发送失败');
                    // 刷新验证码
                    this.refreshCaptcha();
                }
            },
            error: (xhr) => {
                this.hideLoading($btn);
                let errorMsg = '网络错误，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg);
                // 刷新验证码
                this.refreshCaptcha();
            }
        });
    },

    // 更新邮箱
    updateEmail() {
        const email = $('#email-input').val().trim();
        const code = $('#email-code').val().trim();
        const token = $('#email-token').val();

        if (!this.validateEmail(email)) {
            showError('请输入正确的邮箱格式');
            return;
        }

        if (!code) {
            showError('请输入邮箱验证码');
            return;
        }

        // 获取保存按钮，使用更可靠的选择器
        const $btn = $('#email-form').find('button:contains("保存")');
        this.showLoading($btn);

        $.ajax({
            url: '/web/user/bindEmail',
            type: 'POST',
            data: {
                email: email,
                code: code,
                token: token
            },
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);

                if (res.code === 1) {
                    showSuccess('邮箱绑定成功');
                    // 更新页面上的邮箱
                    $('#currentEmail').text(email);
                    modal.hide();
                } else {
                    showError(res.msg || '邮箱绑定失败');
                }
            },
            error: (xhr) => {
                this.hideLoading($btn);
                let errorMsg = '网络错误，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg);
            }
        });
    },

    // 打开修改密码模态框
    openPasswordModal() {
        // 检查是否已绑定邮箱
        const currentEmail = $('#currentEmail').text().trim();
        if (!currentEmail || currentEmail === '未绑定') {
            showError('请先绑定邮箱后再修改密码');
            return;
        }

        const content = `
            <div class="bg-white rounded-2xl shadow-2xl max-w-lg w-full overflow-hidden">
                <div class="bg-blue-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">修改密码</h3>
                    <button onclick="modal.hide()"
                        class="w-8 h-8 rounded-full hover:bg-blue-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-6">
                    <div class="mb-4 p-3 bg-blue-50 border border-blue-200 rounded-lg">
                        <p class="text-sm text-blue-700">
                            <i class="fas fa-info-circle mr-2"></i>
                            为了您的账户安全，修改密码需要邮箱验证码确认
                        </p>
                    </div>
                    <form id="password-form">
                        <div class="mb-5">
                            <label for="password-email-code" class="block text-sm font-medium text-blue-600 mb-2">邮箱验证码</label>
                            <div class="flex gap-2">
                                <input type="text" id="password-email-code" class="flex-1 px-4 py-3 border border-gray-300 rounded-xl" placeholder="请输入验证码">
                                <button type="button" id="send-password-code-btn" class="px-4 py-3 bg-gray-100 border border-gray-300 rounded-xl hover:bg-gray-200 whitespace-nowrap transition-all" onclick="sendPasswordEmailCode()">
                                    获取验证码
                                </button>
                            </div>
                            <p class="text-xs text-gray-500 mt-1">验证码将发送到：${currentEmail}</p>
                        </div>
                        <div class="mb-5">
                            <label for="new-password" class="block text-sm font-medium text-blue-600 mb-2">新密码</label>
                            <div class="relative">
                                <input type="password" id="new-password" class="w-full px-4 py-3 border border-gray-300 rounded-xl pr-10" placeholder="请输入新密码">
                                <button type="button" class="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                        onclick="togglePasswordVisibility('new-password', 'new-password-icon')">
                                    <i id="new-password-icon" class="fas fa-eye"></i>
                                </button>
                            </div>
                            <div class="text-sm text-gray-500 mt-2">密码长度6-20个字符，建议使用字母、数字和符号组合</div>
                        </div>
                        <div class="mb-6">
                            <label for="confirm-password" class="block text-sm font-medium text-blue-600 mb-2">确认新密码</label>
                            <div class="relative">
                                <input type="password" id="confirm-password" class="w-full px-4 py-3 border border-gray-300 rounded-xl pr-10" placeholder="请再次输入新密码">
                                <button type="button" class="absolute right-4 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600"
                                        onclick="togglePasswordVisibility('confirm-password', 'confirm-password-icon')">
                                    <i id="confirm-password-icon" class="fas fa-eye"></i>
                                </button>
                            </div>
                        </div>
                        <div class="flex gap-3">
                            <button type="button" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all" onclick="modal.hide()">取消</button>
                            <button type="button" class="flex-1 py-3 px-4 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-all" onclick="updatePassword()">保存</button>
                        </div>
                    </form>
                </div>
            </div>
        `;
        modal.show(content);
    },

    // 切换密码显示/隐藏
    togglePasswordVisibility(inputId, iconId) {
        const passwordInput = document.getElementById(inputId);
        const passwordIcon = document.getElementById(iconId);
        
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            passwordIcon.classList.remove('fa-eye');
            passwordIcon.classList.add('fa-eye-slash');
        } else {
            passwordInput.type = 'password';
            passwordIcon.classList.remove('fa-eye-slash');
            passwordIcon.classList.add('fa-eye');
        }
    },

    // 更新密码
    updatePassword() {
        const code = $('#password-email-code').val().trim();
        const newPassword = $('#new-password').val().trim();
        const confirmPassword = $('#confirm-password').val().trim();

        if (!code) {
            showError('请输入邮箱验证码');
            return;
        }

        if (!newPassword) {
            showError('请输入新密码');
            return;
        }

        if (newPassword.length < 6) {
            showError('密码长度不能少于6个字符');
            return;
        }

        if (newPassword.length > 20) {
            showError('密码长度不能超过20个字符');
            return;
        }

        if (newPassword !== confirmPassword) {
            showError('两次输入的密码不一致');
            return;
        }

        // 获取保存按钮，使用更可靠的选择器
        const $btn = $('#password-form').find('button:contains("保存")');
        this.showLoading($btn);

        $.ajax({
            url: '/web/user/changePassword',
            type: 'POST',
            data: {
                code: code,
                new_password: newPassword
            },
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);

                if (res.code === 1) {
                    showSuccess('密码修改成功');
                    // 清空输入框
                    $('#password-email-code').val('');
                    $('#new-password').val('');
                    $('#confirm-password').val('');
                    modal.hide();
                } else {
                    showError(res.msg || '密码修改失败');
                }
            },
            error: (xhr) => {
                this.hideLoading($btn);
                let errorMsg = '网络错误，请稍后重试';
                if (xhr.responseJSON && xhr.responseJSON.msg) {
                    errorMsg = xhr.responseJSON.msg;
                }
                showError(errorMsg);
            }
        });
    },

    // 发送修改密码的邮箱验证码
    sendPasswordEmailCode() {
        const currentEmail = $('#currentEmail').text().trim();

        // 先获取图形验证码
        this.showCaptchaModal(currentEmail, 'change_password');
    },

    // 发送邮箱验证码后的处理
    handleCodeSent(type) {
        let $codeBtn;
        if (type === 'bind') {
            $codeBtn = $('#send-code-btn');
        } else if (type === 'change_password') {
            $codeBtn = $('#send-password-code-btn');
        } else if (type === 'verify_old_email') {
            $codeBtn = $('#verify-old-email-btn');
        }
        
        if ($codeBtn && $codeBtn.length > 0) {
            this.startCountdown($codeBtn);
        }
    },

    // 打开退出登录确认模态框
    openLogoutModal() {
        const content = `
            <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full overflow-hidden">
                <div class="bg-red-500 px-6 py-4 flex items-center justify-between">
                    <h3 class="text-xl font-bold text-white">退出登录</h3>
                    <button onclick="modal.hide()" 
                        class="w-8 h-8 rounded-full hover:bg-red-600 transition-colors flex items-center justify-center">
                        <i class="fas fa-times text-white"></i>
                    </button>
                </div>
                <div class="p-6 text-center">
                    <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-sign-out-alt text-red-500 text-xl"></i>
                    </div>
                    <h4 class="text-xl font-bold text-blue-600 mb-3">确认退出登录？</h4>
                    <p class="text-gray-500 mb-6">退出后将返回到网站首页</p>
                    <div class="flex gap-3">
                        <button onclick="modal.hide()" class="flex-1 py-3 px-4 border-2 border-gray-300 rounded-lg text-gray-500 hover:bg-gray-50 transition-all">
                            取消
                        </button>
                        <button onclick="confirmLogout()" class="flex-1 py-3 px-4 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-all">
                            确认退出
                        </button>
                    </div>
                </div>
            </div>
        `;
        modal.show(content);
    },

    // 确认退出登录
    confirmLogout() {
        const $btn = $('button:contains("确认退出")');
        this.showLoading($btn);
        
        $.ajax({
            url: '/api/user/logout',
            type: 'POST',
            dataType: 'json',
            success: (res) => {
                this.hideLoading($btn);
                
                if (res.code === 0) {
                    modal.hide();
                    showSuccess('退出成功，正在跳转...');
                    setTimeout(() => {
                        window.location.href = '/';
                    }, 1000);
                } else {
                    showError(res.msg || '退出失败');
                }
            },
            error: () => {
                this.hideLoading($btn);
                showError('网络错误，请稍后重试');
            }
        });
    },

    // 倒计时
    startCountdown($btn, seconds = 60) {
        $btn.prop('disabled', true);
        const originalText = $btn.html();
        
        let countdown = seconds;
        $btn.html(`${countdown}秒后重新获取`);
        
        const timer = setInterval(() => {
            countdown--;
            $btn.html(`${countdown}秒后重新获取`);
            
            if (countdown <= 0) {
                clearInterval(timer);
                $btn.prop('disabled', false);
                $btn.html(originalText);
            }
        }, 1000);
    },

    // 验证邮箱格式
    validateEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    },

    // 显示加载状态
    showLoading($btn) {
        $btn.prop('disabled', true);
        $btn.data('original-text', $btn.html());
        $btn.html('<i class="fas fa-spinner fa-spin"></i> 处理中...');
    },

    // 隐藏加载状态
    hideLoading($btn) {
        $btn.prop('disabled', false);
        $btn.html($btn.data('original-text') || '保存');
    },

};

// 页面加载完成后初始化
$(document).ready(function() {
    UserCenter.init();
});

// 导出给全局使用的方法
window.updateAvatar = function() {
    UserCenter.updateAvatar();
};

window.updateNickname = function() {
    UserCenter.updateNickname();
};

window.updateEmail = function() {
    UserCenter.updateEmail();
};

window.updatePassword = function() {
    UserCenter.updatePassword();
};

window.confirmLogout = function() {
    UserCenter.confirmLogout();
};

window.togglePasswordVisibility = function(inputId, iconId) {
    UserCenter.togglePasswordVisibility(inputId, iconId);
};

window.sendEmailCode = function() {
    UserCenter.sendEmailCode();
};

window.sendPasswordEmailCode = function() {
    UserCenter.sendPasswordEmailCode();
};

window.refreshCaptcha = function() {
    UserCenter.refreshCaptcha();
};

window.submitCaptcha = function(email, type, captchaKey) {
    UserCenter.submitCaptcha(email, type, captchaKey);
};

window.sendVerifyOldEmailCode = function() {
    UserCenter.sendVerifyOldEmailCode();
};

window.verifyOldEmail = function() {
    UserCenter.verifyOldEmail();
};
